﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Gqq.Csharpindepth.Chapter8910
{
    public class AnonymousUtil
    {
        public static void AnonyTest()
        {
            //通过数组定义了四个人
            var persons = new[]
                              {
                                  new {Name = "Zhangsan", Age = 27},
                                  new {Name = "lisi", Age = 21},
                                  new {Name = "wangwu", Age = 23},
                                  new {Name = "angwu", Age = 23},
                                  new {Name = "sdfew", Age = 23},
                                  new {Name = "sdfds", Age = 21},
                                  new {Name = "wangwu", Age = 27},
                                  new {Name = "sd", Age = 23},
                                  new {Name = "dsfw", Age = 24},
                                  new {Name = "wangwu", Age = 23},
                                  new {Name = "huliu", Age = 28}
                              };

//            foreach (var person in persons)
//            {
//                Console.WriteLine("Name:{0},Age{1}", person.Name, person.Age);
//            }

            var stats = persons
                .GroupBy(a => a.Age)
                .Select(x => new
                                 {
                                     x.Key,
                                     //获得key下的所有的元素,并排序
                                     Values = x.AsEnumerable().OrderBy(p => p.Name),
                                     Count = x.Count()
                                 })
                .OrderByDescending(x => x.Count);
            foreach (var stat in stats)
            {
                Console.WriteLine("Key:{0},Count:{1}", stat.Key, stat.Count);
                foreach (var value in stat.Values)
                {
                    Console.WriteLine("----------------------" + value.Name);
                }
            }
        }
    }
}
